package com.dawn.module.hospital.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.module.hospital.controller.app.tools.vo.AppToolsOcrReqVO;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.service.ehealth.HealthCardService;
import com.dawn.module.hospital.service.ehealth.bean.OcrReq;
import com.dawn.module.hospital.service.ehealth.bean.QRCodeReq;
import com.dawn.module.hospital.service.ehealth.bean.ReportDataReq;
import com.dawn.module.infra.api.file.FileApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Base64;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/10/18 10:30
 */
@Slf4j
@Service
public class ToolsService extends BHService {

    @Resource
    @Lazy
    private HealthCardService healthCardService;

    @Resource
    private FileApi fileApi;

    public CommonResult ocr(AppToolsOcrReqVO reqVO) {
        OcrReq ocrReq = new OcrReq();
        if (getEhealthCfg() != null) {
            ocrReq.setAppId(getEhealthCfg().getAppId());
            ocrReq.setAppSecret(getEhealthCfg().getAppSecret());
            ocrReq.setHospitalId(getEhealthCfg().getHospitalId());
        }
        ocrReq.setImageContent(reqVO.getImg());
        CommonResult result = healthCardService.ocrInfo(ocrReq);
        return result;
    }

    public CommonResult ocrIdCard(AppToolsOcrReqVO reqVO) {
        CommonResult result = CommonResult.error(ERROR_CODE,"ocr 识别失败");
        try {
            byte[] content = fileApi.getFileByUrl(reqVO.getImgUrl());
            String base64String = Base64.getEncoder().encodeToString(content);
            log.warn("********** ocrIdCard **********base64String:"+base64String);
            OcrReq ocrReq = new OcrReq();
            if (getEhealthCfg() != null) {
                ocrReq.setAppId(getEhealthCfg().getAppId());
                ocrReq.setAppSecret(getEhealthCfg().getAppSecret());
                ocrReq.setHospitalId(getEhealthCfg().getHospitalId());
            }
            ocrReq.setImageContent(base64String);
            result = healthCardService.ocrInfo(ocrReq);
        } catch (Exception e) {
            result = CommonResult.error(ERROR_CODE,e.getMessage());
        }
        return result;
    }
}
